from pylab import *
import scipy.stats
import os
import sys


def calculateFilesMean(filesMap):
    
    filesMeans = {}
    for key in filesMap.keys():
        filesData = filesMap[key]
        
        error = mean_confidence_interval(filesData)
        print "KEY: "+str(key)+" "+str(error)
        
        sum = 0
        for value in filesData:
            sum += value
        filesMeans[key] = sum / len(filesData)
    return filesMeans            

def mean_confidence_interval(data, confidence=0.80):
   import scipy.stats
   from numpy import mean, array, sqrt

   a = 1.0*array(data)
   n = len(a)
   m, se = mean(a), scipy.stats.stderr(a)

   # calls the inverse CDF of the Student's t distribution
   h = se * scipy.stats.t._ppf((1+confidence)/2., n-1)
   return h

def createGraphics(map):
    
    xValues = [float(value) for value in map.keys()]
    xValues.sort()
    allMeansPerFileCS = {}
    allMeansPerFileP2P = {}
    
    for size in xValues:
        
        intSize = int(size)
        csData, p2pData = map[str(intSize)]
        
        for file in ["F1", "F2", "F3", "F4", "F5"]:
            fileData = allMeansPerFileCS.get(file)
            if fileData == None:
                fileData = []
                allMeansPerFileCS[file] = fileData
            fileData.append(csData.get(file, 0.0))
        
        for file in ["F1", "F2", "F3", "F4", "F5"]:
            fileData = allMeansPerFileP2P.get(file)
            if fileData == None:
                fileData = []
                allMeansPerFileP2P[file] = fileData
            fileData.append(p2pData.get(file, 0.0))        
        
    #Creating graphics
    figure(figsize = (10, 8))
    f = subplot(211)
    subplots_adjust(left=0.08, bottom=None, right=0.95, top=None,
                wspace=0.4, hspace=0.4)
    
    fileData = allMeansPerFileCS["F1"]
    plot(xValues, fileData, "r--o", label=str("F1"))
    fileData = allMeansPerFileCS["F2"]
    plot(xValues, fileData, "g--o", label=str("F2"))
    fileData = allMeansPerFileCS["F3"]
    plot(xValues, fileData, "b--o", label=str("F3"))
    fileData = allMeansPerFileCS["F4"]
    plot(xValues, fileData, "k--^", label=str("F4"))
    fileData = allMeansPerFileCS["F5"]
    plot(xValues, fileData, "m--^", label=str("F5"))
    
    xlabel("Tamanho dos arquivos (KB)")
    ylabel("Tempo de Resposta (s)")
    title("Modo Cliente/Servidor")
    f.grid(True)
    
    
    f = subplot(212)
    fileData = allMeansPerFileP2P["F1"]
    plot(xValues, fileData, "r--o", label=str("F1"))
    fileData = allMeansPerFileP2P["F2"]
    plot(xValues, fileData, "g--o", label=str("F2"))
    fileData = allMeansPerFileP2P["F3"]
    plot(xValues, fileData, "b--o", label=str("F3"))
    fileData = allMeansPerFileP2P["F4"]
    plot(xValues, fileData, "k--^", label=str("F4"))
    fileData = allMeansPerFileP2P["F5"]
    plot(xValues, fileData, "m--^", label=str("F5"))
    axis([1000, 9000, 5, 30])
    
    xlabel("Tamanho dos arquivos (KB)")
    ylabel("Tempo de Resposta (s)")
    title("Modo P2P")
    f.grid(True)    
    
    savefig("filesDurations")

if __name__ == "__main__":
    
    if len(sys.argv) < 2:
        print "Should give at least two durations files (CS and P2P)!"
        sys.exit(1)
    
    files = sys.argv[1:]
    
    map = {}
    
    for i in xrange(0, len(files), 2):
        file1 = files[i]#CS file
        file2 = files[i+1]# P2P file
        
        size = file1.split("_")[1]
        
        if not os.path.exists(file1) or not os.path.exists(file2):
            print "Inexistent data files!!!"
            sys.exit(1)
        
        #Reading duration data
        handle = open(file1,"r")
        durationsMap = {}
        for line in handle.readlines():
            client, file, duration = line.split()
            fileData = durationsMap.get(file)
            if fileData == None:
                fileData = []
                durationsMap[file] = fileData
            
            fileData.append(float(duration))
        handle.close()
        
        print ">> SIZE"+str(size)+" CS"
        means1 = calculateFilesMean(durationsMap)
        
        #File 2
        handle = open(file2,"r")
        durationsMap2 = {}
        for line in handle.readlines():
            client, file, duration = line.split()
            fileData = durationsMap2.get(file)
            if fileData == None:
                fileData = []
                durationsMap2[file] = fileData
            
            fileData.append(float(duration)) 
        
        print ">> SIZE"+str(size)+" P2P"
        means2 = calculateFilesMean(durationsMap2)
        
        map[size] = (means1, means2)
    
    createGraphics(map)
